using System;
using System.IO;
using System.Reflection;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;

namespace NetFramework.Configuration
{
	/// <summary>
	/// Summary description for ValidatingXmlConfigSectionHandler.
	/// </summary>
	public class ValidatingXmlConfigSectionHandler : IConfigurationSectionHandler
	{
		private Type _configType = null;
		private string _schemaResourceName = string.Empty;
		private string _schemaNamespace = string.Empty;

		public ValidatingXmlConfigSectionHandler(Type configType, 
			string schemaResourceName,  string schemaNamespace)
		{
			if(configType == null)
				throw new ArgumentException("configType should be specified.");
			if(schemaResourceName == null || schemaResourceName == string.Empty)
				throw new ArgumentException("schemaResourceName should be specified.");
			if(schemaNamespace == null || schemaNamespace == string.Empty)
				throw new ArgumentException("schemaNamespace should be specified.");

			_configType = configType;
			_schemaResourceName = schemaResourceName;
			_schemaNamespace = schemaNamespace;
		}

		#region IConfigurationSectionHandler Members

		public object Create(object parent, object configContext, System.Xml.XmlNode section)
		{
			object settings = null;

			XmlSerializer ser = new XmlSerializer(_configType);

			XmlValidatingReader vr = new XmlValidatingReader(new XmlTextReader(
				new StringReader(section.OuterXml)));
			vr.ValidationType = ValidationType.Schema;
		
			Stream schemaStream = Assembly.GetAssembly(_configType)
				.GetManifestResourceStream(_schemaResourceName);

			XmlTextReader sr = new XmlTextReader(schemaStream);

			vr.Schemas.Add(_schemaNamespace, sr);

			settings = ser.Deserialize(vr);

			return settings;
		}

		#endregion
	}
}
